package jnpf.base.util;

import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import jnpf.database.entity.DbLinkEntity;
import jnpf.database.source.DbBase;
import jnpf.database.util.DataSourceUtil;
import jnpf.database.util.DbTypeUtil;
import jnpf.util.StringUtil;
import jnpf.util.context.SpringContext;

/**
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2021/3/12 15:31
 */
public class SourceUtil {

    public DataSourceConfig dbConfig(String dbName) {
        DataSourceConfig dsc = new DataSourceConfig();
        try {
            DataSourceUtil dataSourceUtil = SpringContext.getBean(DataSourceUtil.class);
            DbBase dbBase = DbTypeUtil.getDb(dataSourceUtil);
            dsc.setDbType(dbBase.getMpDbType());
            dsc.setDriverName(dbBase.getDriver());
            dsc.setUsername(dataSourceUtil.getUserName());
            dsc.setPassword(dataSourceUtil.getPassword());
            if (StringUtil.isEmpty(dbName)) {
                dbName = dataSourceUtil.getDbName();
            }
            dsc.setUrl(DbTypeUtil.getUrl(dataSourceUtil, dbName));
        } catch (Exception e) {
            e.getStackTrace();
        }
        return dsc;
    }

    public DataSourceConfig dbConfig(DbLinkEntity linkEntity) {
        DataSourceConfig dsc = new DataSourceConfig();
        try {
            DbBase dbBase = DbTypeUtil.getDb(linkEntity);
            dsc.setDbType(dbBase.getMpDbType());
            dsc.setDriverName(dbBase.getDriver());
            dsc.setUsername(linkEntity.getUserName());
            dsc.setPassword(linkEntity.getPassword());
            dsc.setUrl(DbTypeUtil.getUrl(linkEntity));
        } catch (Exception e) {
            e.getStackTrace();
        }
        return dsc;
    }

    public DataSourceConfig dbConfig(String dbName, DbLinkEntity linkEntity) {
        if (linkEntity != null) {
            return dbConfig(linkEntity);
        } else {
            return dbConfig(dbName);
        }
    }

}
